var orderData = localStorage.getItem('order'),
    addrId = getURLParameter('aId');
if(orderData){
    orderData = JSON.parse(orderData);
}

var ConfirmHeader = React.createClass({
    handleBackOffClick: function(){
        //查看商品信息列表
        window.location.replace('cart.html');
    },
    render: function(){
        return(
            <header data-am-widget="header" className="am-header am-header-default am-header-fixed am-no-layout">
                <div className="am-header-left am-header-nav"><a onClick={this.handleBackOffClick}><i className="icon_8"></i></a></div>
                <h1 className="am-header-title">确认订单</h1>
            </header>
        )
    }
});

var ConfirmAddress = React.createClass({
    handleAddressClick: function() {
        // window.location.href = 'addressList.html?from='+FROM.confirm;
        window.location.replace('addressList.html?from='+FROM.confirm);
    },
    render: function(){
        var curAddr = this.props.detail;
        return (
            <div onClick={this.handleAddressClick} className="bg-white font-14 am-padding-sm prelative">
                <div className="box"><div>联系人：{curAddr.reciver_name + (curAddr.phone ? '（'+curAddr.phone+'）' : '')}</div></div>
                <div className="box am-margin-top-xs">
                    <div className="shouye_100 am-margin-right-xs"></div>
                    <div>地址：{curAddr.location + ' ' + curAddr.detail}</div>
                </div>
                <i className="icon-arrow-right-3"></i>
            </div>
        )
    }
});

var ConfirmGoodsImgs = React.createClass({
    handleGoodsClick: function(){
        //查看商品信息列表
        window.location.href='confirmGoods.html';
    },
    render: function () {
        var count = 0, imgList = [];
        this.props.offers.forEach(function(value){
            imgList.push(
                <div className="am-u-sm-4 am-padding-right-0"><img className="am-img-responsive" src={IMG_PRE+value.img}/></div>
            );
            value.specs.forEach(function(item){
                count += parseInt(item.number);
            });
        });
        return (
            <div className="bg-white box am-padding-top-sm am-padding-bottom-sm prelative" onClick={this.handleGoodsClick}>
                <div className="box-1">
                    <div className="am-g">
                        {imgList}
                    </div>
                </div>
                <div className="am-margin-left-sm am-padding-right-lg am-padding-top-sm">
                    <div className="font-12 font-color-1 am-margin-top-ss">{count}双</div>
                    <div className="font-14 font-color-monney">¥{this.props.price}</div><i className="icon-arrow-right-0"></i>
                </div>
            </div>
        )
    }
});

var ConfirmPrice = React.createClass({
    handleRedirectClick: function() {
        location.href = 'yfsm.html';
    },
    render: function () {
        return (
            <div className="bg-white am-margin-top-sm font-15">
                <div className="box border-bottom am-padding-top-ss am-padding-bottom-ss prelative" onClick={this.handleRedirectClick}>
                    <div className="box-1 am-padding-left-sm">运费</div>
                    <div className="font-color-monney am-padding-right-lg">¥{parseFloat(this.props.freight).toFixed(2)}</div>
                </div>
                <div className="box border-bottom am-padding-top-ss am-padding-bottom-ss prelative">
                    <div className="box-1 am-padding-left-sm">优惠{this.props.cutInfo}</div>
                    <div className="font-color-monney am-padding-right-lg">-¥{parseFloat(this.props.cutPrice).toFixed(2)}</div>
                </div>
                <div className="box am-padding-top-ss am-padding-bottom-ss">
                    <div className="padding-top-3 am-padding-left-sm">留言备注</div>
                    <div className="box-1 am-margin-left-sm"><textarea className="teshu-yaoqiu" id="remark" rows="3" placeholder="请输入您的意见或问题，我们将及时跟进处理。"></textarea></div>
                </div>
            </div>
        )
    }
});

var ConfirmFooter = React.createClass({
    handlePayClick: function(){
        this.props.confirm();
    },
    render: function(){
        return (
            <footer data-am-widget="navbar" className="am-navbar am-cf am-navbar-default bg-white am-no-layout">
                <div className="box">
                    <div className="box-1 am-padding-left-sm font-15">合计：<span className="font-color-monney font-18">¥{parseFloat(this.props.totalPrice).toFixed(2)}</span></div>
                    <div onClick={this.handlePayClick} className="am-padding-left-sm am-padding-right-sm bg-2 font-color-white line-51 ">结算付款</div>
                </div>
            </footer>
        )
    }
});

var Page = React.createClass({
    getInitialState: function() {
        return{
            msg: '',
            msgHidden: true,
            price: orderData.price,
            freight: 0, //运费
            totalPrice: orderData.price,
            offers: orderData.offers,
            addrDetail: {
                reciver_name: '',
                phone: '',
                location: '',
                detail: ''
            },
            cutInfo: '', //优惠信息文字
            cutPrice: 0 //优惠金额
        }
    },
    componentWillMount: function(){
        //获取地址信息
        this.getAddrList();
    },
    showMsg: function(msg) {
        this.setState({
            msg: msg,
            msgHidden: false
        });
        return false;
    },
    closeMsg: function(){
        this.setState({
            msgHidden: true
        });
    },
    getFreight: function(){
        $.ajax(
            getAjaxOps('/order/initDataForOrderCommit', {
                addrId: addrId,
                userId: USER.userId
            })
        ).done(function (res) {
                if(res.resultCode == 0 && res.data.postageSettingses){
                    var topLine = parseFloat(res.data.postageSettingses.status == "1" ? res.data.postageSettingses.top_line : 0);
                    //订单优惠信息
                    if(topLine > 0 && this.state.price >= topLine){
                        var freight = res.data.postageSettingses.price;
                        this.setState({
                            cutInfo: '（满'+topLine.toFixed(2)+'包邮）',
                            freight: freight,
                            cutPrice: freight
                        });
                    }else {
                        this.setState({
                            freight: res.data.postageSettingses.price,
                            totalPrice: this.state.price + res.data.postageSettingses.price //商品价格+运费
                        });
                    }
                }
            }.bind(this));
    },
    getAddrList: function(){
        if(addrId){
            $.ajax(
                getAjaxOps('/address/getAddressById', {
                    addressId: addrId
                })
            ).done(function (res) {
                if(res.resultCode == 0){
                    this.setState({
                        addrDetail: res.data
                    });
                }
            }.bind(this));
            this.getFreight();
        }else {
            $.ajax(
                getAjaxOps('/address/qryAddressList', {
                    userId: USER.userId
                })
            ).done(function (res) {
                if(res.resultCode == 0 && res.data.length > 0){
                    var addrs = res.data, l = addrs.length;
                    for(var i = 0; i<l; i ++){
                        var value = addrs[i];
                        if( value.default == '1'){
                            addrId = value.id;
                            this.setState({
                                addrDetail: value
                            });
                            this.getFreight();
                            break;
                        }
                    }
                }
            }.bind(this));
        }
    },
    confirm: function() {
        if(!addrId || addrId === null){
            //地址不能为空
            this.showMsg('请添加收货地址');
            return false;
        }
        //提交订单确认
        var param = {
            userId: USER.userId,
            addressId: addrId,
            remark: document.getElementById('remark').value,
            price: this.state.totalPrice,
            offers: orderData.offers
        };
        $.ajax(
            getAjaxOps('/order/commitFromCart', {"cartStr":JSON.stringify(param)})
        ).done(function(res){
            if(res.resultCode == 0){
                window.location.href='pay.html?oId='+res.data;
                //清空缓存中的商品数据
                localStorage.removeItem('order');
            }else {
                return this.showMsg(res.resultMsg);
            }
        }.bind(this));
    },
    render: function() {
        return (
            <div>
                <ConfirmHeader/>
                <section data-tag="css-nav">
                    <ConfirmAddress detail={this.state.addrDetail} />
                    <div className="bg-white am-margin-top-sm border-bottom">
                        <div data-am-widget="titlebar" className="am-titlebar am-titlebar-default box prelative am-no-layout">
                            <i className="bgmainblock"></i><h2 className="am-titlebar-title box-1">订单信息</h2>
                        </div>
                    </div>
                    <ConfirmGoodsImgs price={this.state.price} offers={orderData.offers} />
                    <ConfirmPrice price={this.state.price} freight={this.state.freight} cutInfo={this.state.cutInfo} cutPrice={this.state.cutPrice}/>
                    </section>
                <ConfirmFooter totalPrice={this.state.totalPrice} confirm={this.confirm}/>
                <Message msg={this.state.msg} hidden={this.state.msgHidden} close={this.closeMsg} />
            </div>
        )
    }
});

ReactDOM.render(
    <Page />,
    document.getElementById('root')
);